<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 2018/11/6
 * Time: 14:34
 */

namespace common\components\ali;


use common\components\tools\FileHelper;
use common\components\tools\Tools;
use wodrow\yii\rest\ApiException;
use yii\base\Component;
use yii\httpclient\Client;

class AppStore extends Component
{
    const invoiceInfoForCom_TYPE_1 = 1; // (普通发票/电子发票)
    const invoiceInfoForCom_TYPE_2 = 2; // (机动车发票/专用发票)

    /**
     * @return mixed|string
     */
    public static function getToken()
    {
        \Yii::$app->cache->delete('APPSTORE_GET_TOKEN');
        \Yii::$app->cache->delete('APPSTORE_GET_TOKEN_CURL');
        $curl = \Yii::$app->cache->get('APPSTORE_GET_TOKEN_CURL');
        $resp = \Yii::$app->cache->get('APPSTORE_GET_TOKEN');
        if (!$resp || !$curl) {
            $host = "https://ls365vat.market.alicloudapi.com";
            $path = "/getToken";
            $method = "POST";
            $appCode = \common\components\ali\Config::APPSTORE_APPCODE;
            $appKey = \common\components\ali\Config::APPSTORE_APPKEY;
            $appSecret = \common\components\ali\Config::APPSTORE_APPSECRET;
//            Tools::log($appCode);
//            Tools::log($appKey);
//            Tools::log($appSecret);
            $headers = array();
            array_push($headers, "Authorization:APPCODE " . $appCode);
            $querys = "appKey={$appKey}&appSecret={$appSecret}";
            $bodys = "";
            $url = $host . $path . "?" . $querys;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, true);
            if (1 == strpos("$" . $host, "https://")) {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            $resp = curl_exec($curl);
//            Tools::log($resp);
            \Yii::$app->cache->set('APPSTORE_GET_TOKEN_CURL', $curl, 3600 * 24);
            \Yii::$app->cache->set('APPSTORE_GET_TOKEN', $resp, 3600 * 24);
        }
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($resp, 0, $header_size);
        $body = substr($resp, $header_size);
        $resp_arr = json_decode($body, true);
        $token = $resp_arr['token'];
        return $token;
    }

    /**
     * VIN识别接口（提车影像）
     */
    public static function printedWordRecognitionVehicleIdentification($file_path)
    {
        $url = "https://vin.market.alicloudapi.com/api/predict/ocr_vin";
        $appCode = Config::APPSTORE_APPCODE;
        $file = $file_path;
        //如果输入带有inputs, 设置为True，否则设为False
        $is_old_format = false;
        //如果没有configure字段，config设为空
        //$config = array(
        //    "side" => "face"
        //);
        $config = array();
        if ($fp = fopen($file, "rb", 0)) {
            $binary = fread($fp, filesize($file)); // 文件读取
            fclose($fp);
            $base64 = base64_encode($binary); // 转码
        }
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appCode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
        $querys = "";
        if ($is_old_format == TRUE) {
            $request = array();
            $request["image"] = array(
                "dataType" => 50,
                "dataValue" => "$base64"
            );
            if (count($config) > 0) {
                $request["configure"] = array(
                    "dataType" => 50,
                    "dataValue" => json_encode($config)
                );
            }
            $body = json_encode(array("inputs" => array($request)));
        } else {
            $request = array(
                "image" => "$base64"
            );
            if (count($config) > 0) {
                $request["configure"] = json_encode($config);
            }
            $body = json_encode($request);
        }
        $method = "POST";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($httpCode == 200) {
            if ($is_old_format) {
                $output = json_decode($rbody, true);
                $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
            } else {
                $result_str = $rbody;
            }
            if (!$result_str)$result_str='';
            return (string)$result_str;
//            printf("result is :\n %s\n", $result_str);
        } else {
            printf("Http error code: %d\n", $httpCode);
            printf("Error msg in body: %s\n", $rbody);
            printf("header: %s\n", $rheader);
            exit;
        }
    }

    /**
     * 《机动车合格证》二维码解码
     */
    public static function qrCodeTextDecoding($encText)
    {
        $client = new Client();
        $resp = $client->post("https://api.apishop.net/ccdfeege/vin123", [
            'apiKey' => Config::APPSTORE_APPKEY_1,
            'encText' => $encText, // 《机动车合格证》二维码未解码之前的密文，类似：ZCCCHGZ_V3.1 20091013#1280|C206A……
        ])->send();
        $content = $resp->content;
        return $content;
    }

    /**
     * 印刷文字识别-行驶证识别
     */
    public static function printedCharacterRecognitionLicenseRecognition($file_path, $side = 'face')
    {
        $url = "https://dm-53.data.aliyun.com/rest/160601/ocr/ocr_vehicle.json";
        $appCode = Config::APPSTORE_APPCODE;
        $file = $file_path;
        //如果输入带有inputs, 设置为True，否则设为False
        $is_old_format = false;
        //如果没有configure字段，config设为空
        $config = array(
            "side" => $side
        );
        //$config = array()
        if ($fp = fopen($file, "rb", 0)) {
            $binary = fread($fp, filesize($file)); // 文件读取
            fclose($fp);
            $base64 = base64_encode($binary); // 转码
        }
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appCode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
        $querys = "";
        if ($is_old_format == TRUE) {
            $request = array();
            $request["image"] = array(
                "dataType" => 50,
                "dataValue" => "$base64"
            );

            if (count($config) > 0) {
                $request["configure"] = array(
                    "dataType" => 50,
                    "dataValue" => json_encode($config)
                );
            }
            $body = json_encode(array("inputs" => array($request)));
        } else {
            $request = array(
                "image" => "$base64"
            );
            if (count($config) > 0) {
                $request["configure"] = json_encode($config);
            }
            $body = json_encode($request);
        }
        $method = "POST";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($httpCode == 200) {
            if ($is_old_format) {
                $output = json_decode($rbody, true);
                $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
            } else {
                $result_str = $rbody;
            }
            if (!$result_str)$result_str='';
            return (string)$result_str;
//            printf("result is :\n %s\n", $result_str);
        } else {
            printf("Http error code: %d\n", $httpCode);
            printf("Error msg in body: %s\n", $rbody);
            printf("header: %s\n", $rheader);
            exit;
        }
    }

    /**
     * OCR识别-【购车发票识别、机动车发票识别、发票查验、发票验真】
     */
    public static function ocrDistinguishing($file_path, $car_new_or_used)
    {
        $host = "http://gcfp.market.alicloudapi.com";
//        $host = "http://";
        $path = "/invoice/discern";
        $method = "POST";
        $appCode = Config::APPSTORE_APPCODE;
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appCode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
        $querys = "";
//        $bodys = "{\"InvoiceImageUrl\":\"$url\"}";
        $base64 = FileHelper::fileToBase64($file_path);
        $base64 = FileHelper::removeDataHeaderForBase64($base64);
        $bodys = "{\"InvoiceBase64Data\":\"$base64\", \"Category\":\"$car_new_or_used\"}";
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $resp = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($resp, 0, $header_size);
        $body = substr($resp, $header_size);
//        $resp_arr = json_decode($body, true);
//        $token = $resp_arr['token'];
        if (!$body)$body='';
        return (string)$body;
    }

    /**
     * 乐税发票真伪查验接口
     */
    public static function invoiceAuthenticityInspectionInterface()
    {
    }

    /**
     * 扫_描二维码 乐税发票真伪查验接口
     */
    public static function scanQrCodeInvoiceAuthenticityInspectionInterface($scanStr)
    {
        $token = self::getToken();
        $host = "https://ls365vat.market.alicloudapi.com";
        $path = "/api/invoiceInfoByQRCode";
        $method = "POST";
        $appCode = Config::APPSTORE_APPCODE;
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appCode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
        $querys = "";
        $bodys = "{\"scanStr\":\"$scanStr\",\"token\":\"$token\"}";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $resp = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($resp, 0, $header_size);
        $body = substr($resp, $header_size);
        if (!$body)$body='';
        return (string)$body;
    }

    public static function ocrCarInvoice($file_path)
    {
        $host = "https://ocrapi-car-invoice.taobao.com";
        $path = "/ocrservice/carInvoice";
        $method = "POST";
        $appcode = Config::APPSTORE_APPCODE;
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
        $base64 = FileHelper::fileToBase64($file_path);
        $base64 = FileHelper::removeDataHeaderForBase64($base64);
        $bodys = "{\"img\":\"$base64\"}";
//        $bodys = "{//图像数据：base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边最大4096px，支持jpg/png/bmp格式，和url参数只能同时存在一个\"img\":\"\",//图像url地址：图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4M，最短边至少15px，最长边最大4096px，支持jpg/png/bmp格式，和img参数只能同时存在一个\"url\":\"\"}";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $resp = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($resp, 0, $header_size);
        $body = substr($resp, $header_size);
        if (!$body)$body='';
        return (string)$body;
    }

    public static function invoiceInfoForCom($iifc_type, $invoiceCode, $invoiceNumber, $billTime, $checkCode = null, $invoiceAmount = null)
    {
        $host = "https://ls365vat.market.alicloudapi.com";
        $path = "/api/invoiceInfoForCom";
        $method = "POST";
        $appcode = Config::APPSTORE_APPCODE;
        $token = self::getToken();
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
        switch ($iifc_type){
            case self::invoiceInfoForCom_TYPE_1:
                $bodys = "{\"invoiceCode\":\"$invoiceCode\",\"invoiceNumber\":\"$invoiceNumber\",\"billTime\":\"$billTime\",\"checkCode\":\"$checkCode\",\"token\":\"$token\"}";
                break;
            case self::invoiceInfoForCom_TYPE_2:
                $bodys = "{\"invoiceCode\":\"$invoiceCode\",\"invoiceNumber\":\"$invoiceNumber\",\"billTime\":\"$billTime\",\"invoiceAmount\":\"$invoiceAmount\",\"token\":\"$token\"}";
                break;
            default:
                throw new ApiException(201811301113, "没有找到发票类型");
                break;
        }
//        $bodys = "i.请求报文(普通发票/电子发票)：{\"invoiceCode\":\"发票代码\",\"invoiceNumber\":\"发票号码\",\"billTime\":\"开票时间\",\"checkCode\":\"校验码\",\"token\":\"授权码\"}ii.请求报文(机动车发票/专用发票)：{\"invoiceCode\":\"发票代码\",\"invoiceNumber\":\"发票号码\",\"billTime\":\"开票时间\",\"invoiceAmount\":\"开票金额\",\"token\":\"授权码\"}";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $resp = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($resp, 0, $header_size);
        $body = substr($resp, $header_size);
        if (!$body)$body='';
        return (string)$body;
    }

    /**
     * @param $iifc_type
     * @param $invoiceCode
     * @param $invoiceNumber
     * @param $billTime
     * @param null $checkCode
     * @param null $invoiceAmount
     * @throws
     */
    public static function invoiceInfoForCom1($iifc_type, $invoiceCode, $invoiceNumber, $billTime, $checkCode = null, $invoiceAmount = null)
    {
        $token = \Yii::$app->cache->get('invoiceInfoForCom1');
        if (!$token){
            $client = new Client();
            $resp = $client->get('https://open.leshui365.com/getToken', [
                'appKey' => \common\components\ali\Config::APPSTORE_APPKEY,
                'appSecret' => \common\components\ali\Config::APPSTORE_APPSECRET,
            ])->send();
            $arr = json_decode($resp->content, true);
            $token = $arr['token'];
            \Yii::$app->cache->set('invoiceInfoForCom1', $token, 7200);
        }
        switch ($iifc_type){
            case self::invoiceInfoForCom_TYPE_1:
                throw new ApiException(201811301114, "没有找到发票类型 invoiceInfoForCom_TYPE_1");
                break;
            case self::invoiceInfoForCom_TYPE_2:
                $client = new Client();
                $resp = $client->post('https://open.leshui365.com/api/invoiceInfoForCom', [
                    'invoiceCode' => $invoiceCode,
                    'invoiceNumber' => $invoiceNumber,
                    'billTime' => $billTime,
                    'checkCode' => $checkCode,
                    'invoiceAmount' => $invoiceAmount,
                    'token' => $token,
                ])->send();
                return $resp->content;
                break;
            default:
                throw new ApiException(201811301115, "没有找到发票类型");
                break;
        }
    }

    /**
     * wwei_二维码解码
     */
    public static function wweiEncodeErcode($base64 = null)
    {
        $host = "http://qrapi.market.alicloudapi.com";
        $path = "/yunapi/qrdecode.html";
        $method = "POST";
        $appcode = Config::APPSTORE_APPCODE;
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
//        $bodys = "imgurl=http%3A%2F%2Fwww.wwei.cn%2Fstatic%2Fimages%2Fqrcode.jpg&imgdata=data%3Aimage%2Fjpeg%3Bbase64%2C%2F9j%2F...%E7%9C%81%E7%95%A5N%E4%B8%AA%E5%AD%97%E7%AC%A6...V%2F2Q%3D%3D&version=1.1";
//        $file_url = urlencode($file_url);
//        $bodys = "imgurl={$file_url}&version=1.1";
//        $base64 = FileHelper::removeDataHeaderForBase64($base64);
        $base64 = urlencode($base64);
        $bodys = "imgdata={$base64}&version=1.1";
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $resp = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header = substr($resp, 0, $header_size);
        $body = substr($resp, $header_size);
        if (!$body)$body='';
        return (string)$body;
    }
}